package adv7.bank;

import java.util.Random;

public class Taker extends Thread {
	private Account ac;
	private boolean isTaken = true;

	public Taker(Account ac, String name) {
		super(name);
		this.ac = ac;
	}

	public void takeMoney(int m) {
		System.out.println(super.getName() + "准备取钱" + m + "元，现在余额是"
				+ ac.getMoney() + "元");
		synchronized (ac) {// 加锁，被别人占用，会等待
			if (ac.getMoney() >= m) {// 余额不可能是负数
				try {
					sleep((long) (100 * Math.random()));
				} catch (InterruptedException e) {
					// TODO 自动生成的 catch 块
					e.printStackTrace();
				}

				ac.takeMoney(m);
				System.out.println(super.getName() + "取钱" + m + "元成功，现在余额是"
						+ ac.getMoney() + "元");
			} else {
				System.out.println(super.getName() + "计划取钱" + m
						+ "元失败，余额不足，现在余额是" + ac.getMoney() + "元");
				isTaken = false;
			}
		}// 释放锁
	}

	@Override
	public void run() {
		Random r = new Random();
		while (isTaken) {
			int m = r.nextInt(400);
			takeMoney(m);
		}
	}
}
